<template>
	<view class="container">
		<!-- 头部导航 -->
		<!-- <view class="header">
			<image src="/static/icon-Get-into@3.png" class="back-btn" @click="goBack"></image>
			<text class="page-title">填写保单信息</text>
		</view> -->

		<!-- 表单内容 -->
		<view class="form-wrapper">
			<!-- 基本信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">姓名:</text>
					<input v-model="formData.myname" type="text" class="input" placeholder="请输入姓名" :disabled="isPreview" />
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">身份证号:</text>
					<input v-model="formData.idcardNum" type="text" class="input" placeholder="请输入身份证号" :disabled="isPreview" />
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">卡号:</text>
					<input v-model="formData.cardId" type="text" class="input" placeholder="请输入卡号" :disabled="isPreview" />
				</view>
			</view>

			<!-- 联系信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">手机号:</text>
					<input v-model="formData.phoneNum" type="text" class="input" placeholder="请输入手机号" :disabled="isPreview" />
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">婚姻情况:</text>
					<view class="radio-group">
						<view class="radio-item" :class="{ active: formData.is_marry === '1' }" @click="selectMarriage('1')">
							<text>未婚</text>
						</view>
						<view class="radio-item" :class="{ active: formData.is_marry === '2' }" @click="selectMarriage('2')">
							<text>已婚</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 地址信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">户籍地址:</text>
					<input v-model="formData.P_address" type="text" class="input" placeholder="请输入您的户籍地址" :disabled="isPreview" />
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">现居地址:</text>
					<input v-model="formData.N_address" type="text" class="input" placeholder="请选择" readonly @click="selectRegion" />
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">详细地址:</text>
					<input v-model="formData.D_address" type="text" class="input" placeholder="请输入您的详细地址" :disabled="isPreview" />
				</view>
			</view>

			<!-- 身份证照片 -->
			<view class="photo-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>手持身份证拍照</text>
				</view>
				<view class="photo-group">
					<view class="photo-item" @click="selectPhoto('idfront')">
						<image :src="formData.idfront || '/static/icon-sfz(fan)@2x.png'" class="photo-img"></image>
						<text class="photo-label">身份证正面</text>
					</view>
					<view class="photo-item" @click="selectPhoto('idback')">
						<image :src="formData.idback || '/static/icon-sfz(zheng)@2x.png'" class="photo-img"></image>
						<text class="photo-label">身份证反面</text>
					</view>
				</view>
			</view>

			<!-- 电子签名 -->
			<view class="signature-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>本人签名</text>
				</view>
				<view class="signature-box" @click="openSignature">
					<image v-if="formData.nameP" :src="formData.nameP" class="signature-img"></image>
					<text v-else class="signature-placeholder">点击签名</text>
				</view>
			</view>

			<!-- 申请日期 -->
			<view class="date-section">
				<text>申请日期：</text>
				<text class="date-text">{{ currentDate }}</text>
			</view>

			<!-- 协议 -->
			<view class="agreement-section">
				<view class="checkbox-item" @click="toggleAgreement">
					<view class="checkbox" :class="{ checked: isAgreed }"></view>
				</view>
				<text class="agreement-text">本人承诺，以上所填信息均属实，所提供的相关资料均真实、有效，如有虚假，愿意承担一切责任。</text>
			</view>

			<!-- 底部按钮 -->
			<view class="button-group">
				<button v-if="!isPreview" class="btn preview-btn" @click="previewForm">预览</button>
				<button v-if="isPreview" class="btn edit-btn" @click="editForm">返回编辑</button>
				<button class="btn submit-btn" @click="submitForm">{{ isPreview ? '确认提交' : '提交' }}</button>
			</view>
		</view>

		<!-- 地区选择器 -->
		<uni-popup ref="regionPopup" type="bottom">
			<view class="region-picker">
				<view class="picker-header">
					<text class="picker-cancel" @click="cancelRegionSelect">取消</text>
					<text class="picker-title">地区选择</text>
					<text class="picker-confirm" @click="confirmRegionSelect">确定</text>
				</view>
				<picker-view v-model="regionValue" class="picker-view">
					<picker-view-column>
						<view v-for="(item, index) in provinces" :key="index" class="picker-item">{{ item.region_name }}</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item, index) in cities" :key="index" class="picker-item">{{ item.region_name }}</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item, index) in districts" :key="index" class="picker-item">{{ item.region_name }}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</uni-popup>

		<!-- 电子签名弹窗 -->
		<uni-popup ref="signaturePopup" type="center">
			<view class="signature-modal">
				<view class="signature-header">
					<image src="/static/icon-Get-into@3.png" class="back-btn" @click="closeSignature"></image>
					<text class="signature-title">电子签名</text>
				</view>
				<canvas canvas-id="signatureCanvas" class="signature-canvas" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
				<view class="signature-buttons">
					<button class="signature-btn clear-btn" @click="clearSignature">清除</button>
					<button class="signature-btn save-btn" @click="saveSignature">完成</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { identityApi, commonApi } from '@/api/index.js'

export default {
	components: {},
	data() {
		return {
			formData: {
				myname: '',
				idcardNum: '',
				cardId: '',
				phoneNum: '',
				is_marry: '1',
				P_address: '',
				N_address: '',
				D_address: '',
				idfront: '',
				idback: '',
				nameP: ''
			},
			isPreview: false,
			isAgreed: false,
			currentDate: '',
			
			// 地区选择相关
			regionValue: [0, 0, 0],
			provinces: [],
			cities: [],
			districts: [],
			selectedRegion: null,
			
			// 签名相关
			ctx: null,
			isDrawing: false,
			lastPoint: { x: 0, y: 0 }
		}
	},
	
	onLoad() {
		this.initCurrentDate()
		this.loadRegionData()
		this.initSignatureCanvas()
	},
	
	methods: {
		// 初始化当前日期
		initCurrentDate() {
			const now = new Date()
			const year = now.getFullYear()
			const month = String(now.getMonth() + 1).padStart(2, '0')
			const day = String(now.getDate()).padStart(2, '0')
			const hours = String(now.getHours()).padStart(2, '0')
			const minutes = String(now.getMinutes()).padStart(2, '0')
			const seconds = String(now.getSeconds()).padStart(2, '0')
			this.currentDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 选择婚姻状况
		selectMarriage(value) {
			if (!this.isPreview) {
				this.formData.is_marry = value
			}
		},
		
		// 选择照片
		selectPhoto(type) {
			if (this.isPreview) return
			
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['camera', 'album'],
				success: (res) => {
					this.uploadImage(res.tempFilePaths[0], type)
				}
			})
		},
		
		// 上传图片
		async uploadImage(filePath, type) {
			uni.showLoading({ title: '上传中...' })
			
			try {
				const result = await this.uploadFile(filePath)
				if (result.r === 0) {
					this.formData[type] = result.data.url
					uni.showToast({ title: '上传成功', icon: 'success' })
				} else {
					uni.showToast({ title: result.msg || '上传失败', icon: 'none' })
				}
			} catch (error) {
				uni.showToast({ title: '上传失败', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		},
		
		// 文件上传
		uploadFile(filePath) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: this.$config.baseUrl + 'home/common/upload_img',
					filePath: filePath,
					name: 'file',
					header: {
						'token': uni.getStorageSync('token')
					},
					success: (res) => {
						try {
							const result = JSON.parse(res.data)
							resolve(result)
						} catch (error) {
							reject(error)
						}
					},
					fail: reject
				})
			})
		},
		
		// 加载地区数据
		async loadRegionData() {
			try {
				const result = await commonApi.getAllRegion()
				if (result.r === 0) {
					this.provinces = result.data.gr
					this.updateCities()
				}
			} catch (error) {
				console.error('加载地区数据失败:', error)
			}
		},
		
		// 更新城市列表
		updateCities() {
			if (this.provinces.length > 0) {
				this.cities = this.provinces[this.regionValue[0]].child || []
				this.updateDistricts()
			}
		},
		
		// 更新区县列表
		updateDistricts() {
			if (this.cities.length > 0) {
				this.districts = this.cities[this.regionValue[1]].child || []
			}
		},
		
		// 选择地区
		selectRegion() {
			if (this.isPreview) return
			this.$refs.regionPopup.open()
		},
		
		// 取消地区选择
		cancelRegionSelect() {
			this.$refs.regionPopup.close()
		},
		
		// 确认地区选择
		confirmRegionSelect() {
			const province = this.provinces[this.regionValue[0]]
			const city = this.cities[this.regionValue[1]]
			const district = this.districts[this.regionValue[2]]
			
			this.formData.N_address = `${province.region_name}-${city.region_name}-${district.region_name}`
			this.selectedRegion = { province, city, district }
			this.$refs.regionPopup.close()
		},
		
		// 监听地区选择变化
		onRegionChange(e) {
			this.regionValue = e.detail.value
			this.updateCities()
		},
		
		// 初始化签名画布
		initSignatureCanvas() {
			this.ctx = uni.createCanvasContext('signatureCanvas', this)
			this.ctx.setStrokeStyle('#000000')
			this.ctx.setLineWidth(4)
			this.ctx.setLineCap('round')
			this.ctx.setLineJoin('round')
		},
		
		// 打开签名弹窗
		openSignature() {
			if (this.isPreview) return
			this.$refs.signaturePopup.open()
		},
		
		// 关闭签名弹窗
		closeSignature() {
			this.$refs.signaturePopup.close()
		},
		
		// 触摸开始
		touchStart(e) {
			this.isDrawing = true
			const touch = e.touches[0]
			this.lastPoint = { x: touch.x, y: touch.y }
		},
		
		// 触摸移动
		touchMove(e) {
			if (!this.isDrawing) return
			
			const touch = e.touches[0]
			const currentPoint = { x: touch.x, y: touch.y }
			
			this.ctx.beginPath()
			this.ctx.moveTo(this.lastPoint.x, this.lastPoint.y)
			this.ctx.lineTo(currentPoint.x, currentPoint.y)
			this.ctx.stroke()
			this.ctx.draw(true)
			
			this.lastPoint = currentPoint
		},
		
		// 触摸结束
		touchEnd() {
			this.isDrawing = false
		},
		
		// 清除签名
		clearSignature() {
			this.ctx.clearRect(0, 0, 300, 200)
			this.ctx.draw()
		},
		
		// 保存签名
		saveSignature() {
			uni.canvasToTempFilePath({
				canvasId: 'signatureCanvas',
				success: (res) => {
					this.uploadImage(res.tempFilePath, 'nameP')
					this.closeSignature()
				}
			}, this)
		},
		
		// 切换协议同意状态
		toggleAgreement() {
			this.isAgreed = !this.isAgreed
		},
		
		// 预览表单
		previewForm() {
			this.isPreview = true
		},
		
		// 编辑表单
		editForm() {
			this.isPreview = false
		},
		
		// 表单验证
		validateForm() {
			if (!this.formData.myname) {
				uni.showToast({ title: '真实姓名不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.idcardNum) {
				uni.showToast({ title: '身份证号码不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.cardId) {
				uni.showToast({ title: '卡号不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.phoneNum) {
				uni.showToast({ title: '手机号不可为空', icon: 'none' })
				return false
			}
			
			const phoneReg = /^1[0-9]\d{9}$/
			if (!phoneReg.test(this.formData.phoneNum)) {
				uni.showToast({ title: '手机号格式错误', icon: 'none' })
				return false
			}
			
			if (!this.formData.P_address) {
				uni.showToast({ title: '户籍地址不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.N_address) {
				uni.showToast({ title: '现居地址不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.D_address) {
				uni.showToast({ title: '详细地址不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.idfront) {
				uni.showToast({ title: '请上传身份证正面照', icon: 'none' })
				return false
			}
			
			if (!this.formData.idback) {
				uni.showToast({ title: '请上传身份证背面照', icon: 'none' })
				return false
			}
			
			if (!this.formData.nameP) {
				uni.showToast({ title: '请填写电子签名', icon: 'none' })
				return false
			}
			
			if (!this.isAgreed) {
				uni.showToast({ title: '请点击阅读同意优享优品市运营协议', icon: 'none' })
				return false
			}
			
			return true
		},
		
		// 提交表单
		async submitForm() {
			if (!this.validateForm()) return
			
			uni.showLoading({ title: '提交中...' })
			
			try {
				const recordId = uni.getStorageSync('record_id')
				const submitData = {
					insurant_realname: this.formData.myname,
					id_number: this.formData.idcardNum,
					phone: this.formData.phoneNum,
					card_num: this.formData.cardId,
					sign_url: this.formData.nameP,
					front_photo: this.formData.idfront,
					back_photo: this.formData.idback,
					marital_state: parseInt(this.formData.is_marry),
					location_address: this.formData.N_address + this.formData.D_address,
					domicile_address: this.formData.P_address,
					record_id: parseInt(recordId)
				}
				
				const result = await identityApi.addInsuranceInfo(submitData)
				
				if (result.r === 0) {
					uni.removeStorageSync('record_id')
					uni.showToast({ title: result.msg || '提交成功', icon: 'success' })
					
					setTimeout(() => {
						uni.navigateTo({ url: '/pages/identity/shenqing_more' })
					}, 2000)
				} else {
					uni.showToast({ title: result.msg || '提交失败', icon: 'none' })
				}
			} catch (error) {
				console.error('提交失败:', error)
				uni.showToast({ title: '提交失败', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 88rpx;
	background-color: #fff;
	position: relative;
	border-bottom: 1rpx solid #eee;
	
	.back-btn {
		position: absolute;
		left: 30rpx;
		width: 40rpx;
		height: 40rpx;
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: 500;
		color: #333;
	}
}

.form-wrapper {
	padding: 20rpx;
}

.form-section {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 0 30rpx;
}

.form-item {
	display: flex;
	align-items: center;
	height: 100rpx;
	border-bottom: 1rpx solid #eee;
	
	&:last-child {
		border-bottom: none;
	}
	
	.required {
		color: #ff4757;
		font-size: 30rpx;
		margin-right: 16rpx;
	}
	
	.label {
		font-size: 28rpx;
		color: #333;
		margin-right: 20rpx;
		min-width: 140rpx;
	}
	
	.input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		
		&:disabled {
			background-color: transparent;
		}
	}
	
	.radio-group {
		display: flex;
		flex: 1;
		
		.radio-item {
			display: flex;
			align-items: center;
			height: 60rpx;
			padding-left: 68rpx;
			margin-right: 60rpx;
			background: url('/static/radio.png') no-repeat left center;
			background-size: 44rpx 44rpx;
			font-size: 28rpx;
			color: #333;
			
			&.active {
				background-image: url('/static/radio-checked.png');
			}
		}
	}
}

.photo-section, .signature-section {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
	
	.section-title {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		
		.required {
			color: #ff4757;
			font-size: 30rpx;
			margin-right: 16rpx;
		}
		
		text {
			font-size: 28rpx;
			color: #333;
		}
	}
}

.photo-group {
	display: flex;
	gap: 40rpx;
	
	.photo-item {
		flex: 1;
		text-align: center;
		
		.photo-img {
			width: 218rpx;
			height: 192rpx;
			border-radius: 8rpx;
			border: 1rpx solid #eee;
		}
		
		.photo-label {
			display: block;
			margin-top: 20rpx;
			font-size: 24rpx;
			color: #666;
		}
	}
}

.signature-box {
	width: 100%;
	height: 192rpx;
	border: 1rpx solid #eee;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.signature-img {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}
	
	.signature-placeholder {
		font-size: 30rpx;
		color: #ccc;
	}
}

.date-section {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
	display: flex;
	align-items: center;
	
	text {
		font-size: 28rpx;
		color: #333;
		
		&.date-text {
			color: #9f9f9f;
		}
	}
}

.agreement-section {
	display: flex;
	align-items: flex-start;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.checkbox-item {
		margin-right: 20rpx;
		margin-top: 10rpx;
		
		.checkbox {
			width: 32rpx;
			height: 32rpx;
			border: 2rpx solid #ddd;
			border-radius: 4rpx;
			background-color: #fff;
			
			&.checked {
				background-color: #1e83d3;
				border-color: #1e83d3;
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					left: 6rpx;
					top: 2rpx;
					width: 12rpx;
					height: 20rpx;
					border: 2rpx solid #fff;
					border-left: none;
					border-top: none;
					transform: rotate(45deg);
				}
			}
		}
	}
	
	.agreement-text {
		flex: 1;
		font-size: 25rpx;
		color: #9f9f9f;
		line-height: 1.6;
	}
}

.button-group {
	display: flex;
	gap: 20rpx;
	padding: 30rpx;
	
	.btn {
		flex: 1;
		height: 88rpx;
		border-radius: 44rpx;
		font-size: 34rpx;
		border: none;
		
		&.preview-btn, &.edit-btn {
			background-color: #f5f5f5;
			color: #333;
		}
		
		&.submit-btn {
			background-color: #1e83d3;
			color: #fff;
		}
	}
}

// 地区选择器样式
.region-picker {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	
	.picker-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		padding: 0 30rpx;
		border-bottom: 1rpx solid #eee;
		
		.picker-cancel, .picker-confirm {
			font-size: 28rpx;
			color: #1e83d3;
		}
		
		.picker-title {
			font-size: 30rpx;
			color: #333;
			font-weight: 500;
		}
	}
	
	.picker-view {
		height: 400rpx;
		
		.picker-item {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 80rpx;
			font-size: 30rpx;
			color: #333;
		}
	}
}

// 签名弹窗样式
.signature-modal {
	width: 90vw;
	height: 70vh;
	background-color: #fff;
	border-radius: 20rpx;
	display: flex;
	flex-direction: column;
	
	.signature-header {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 88rpx;
		border-bottom: 1rpx solid #eee;
		position: relative;
		
		.back-btn {
			position: absolute;
			left: 30rpx;
			width: 40rpx;
			height: 40rpx;
		}
		
		.signature-title {
			font-size: 36rpx;
			font-weight: 500;
			color: #333;
		}
	}
	
	.signature-canvas {
		flex: 1;
		width: 100%;
		background-color: #f9f9f9;
	}
	
	.signature-buttons {
		display: flex;
		gap: 20rpx;
		padding: 30rpx;
		
		.signature-btn {
			flex: 1;
			height: 80rpx;
			border-radius: 40rpx;
			font-size: 30rpx;
			border: none;
			
			&.clear-btn {
				background-color: #f5f5f5;
				color: #333;
			}
			
			&.save-btn {
				background-color: #1e83d3;
				color: #fff;
			}
		}
	}
}
</style>